//
//  ExpendViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/7/3.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//
// FIXME: [Datepicker] picks wrong date if operation time is crossing 12:00PM
//

#import "ExpendViewController.h"

@interface ExpendViewController ()

@end

@implementation ExpendViewController

@synthesize transaction;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.delegate = self;
        
        transaction = nil;
        expendTransactions = [[NSMutableArray alloc] init];
        
        self.tableView.tag = 0;
        
        [self initDatePicker];
        [self initTransPropertyPicker:RootCategoryExpend];
        [self initInputToolbar:RichInputToolbarButtonBack | RichInputToolbarButtonNext | RichInputToolbarButtonDone];
        
        categoryPicker = [[CategoryViewController alloc] initWithStyle:UITableViewStylePlain];
        categoryPicker.mode = RichTableModeListReadonly;
        categoryPicker.level = 1;
        categoryPicker.parentCode = RootCategoryExpend;
        categoryPicker.callerDelegate = self;
        categoryPicker.navigator = self.navigator;
        
        accountPicker = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
        accountPicker.mode = RichTableModeListReadonly;
        accountPicker.callerDelegate = self;
        
        installmentEditor = [[InstallmentViewController alloc] initWithStyle:UITableViewStylePlain];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.mode == RichTableModeUpdate) {
        uint64_t transId;
        
        if (transaction.installmentTransId == 0)
            transId = transaction.transId;
        else
            transId = transaction.installmentTransId;
        
        [[RichDelegate core] loadGeneralTransactions:expendTransactions
                                            category:RootCategoryExpend
                                               where:[NSString stringWithFormat:@"id_pk = %lld or installment_trans_id = %lld", transId, transId]
                                        beginAtIndex:(self.page * ROWS_PER_PAGE)
                                               limit:ROWS_PER_PAGE
                                          descending:NO];
        
        self.transaction = (RichTransactionGeneral *)[[RichDelegate core] findTransactionIn:expendTransactions byID:transId type:kTransactionTypeGeneral];
        
        if (installmentEditor.isModified) {
            // View appear from 'InstallmentViewController'
        }
        else {
            // View appear from 'Update' operation
        }
    }
    else if (self.mode == RichTableModeListEditable || self.mode == RichTableModeListReadonly) {
        [[RichDelegate core] loadGeneralTransactions:expendTransactions
                                            category:RootCategoryExpend
                                               where:@"date <= datetime('now', 'localtime')"
                                        beginAtIndex:(self.page * ROWS_PER_PAGE)
                                               limit:ROWS_PER_PAGE
                                          descending:YES];
        
        if ([expendTransactions count] > 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else
            self.navigationItem.rightBarButtonItem = nil;
    }
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.mode == RichTableModeCreate || self.mode == RichTableModeUpdate)
        return 9;
    else
        return [expendTransactions count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *code;
    UITableViewCell *cell = nil;
    RichTableViewTextfieldCell *textfieldCell = nil;
    
    if (self.mode == RichTableModeCreate || self.mode == RichTableModeUpdate) {
        if ([indexPath row] != 5) {
            tableCellStyle = RichTableCellStyleTextfield;
            textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
            
            cell = textfieldCell;
        }
        
        switch ([indexPath row]) {
            case 0:
                textfieldCell.textLabel.text = RichLocaleString(@"Date");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = datePicker;
                
                if (self.mode == RichTableModeUpdate)
                    textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:transaction.date format:@"yyyy-MM-dd"];
                else
                    textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
                break;
            
            case 1:
                textfieldCell.textLabel.text = RichLocaleString(@"Category");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = categoryPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:transaction.categoryCode]];
                break;
            
            case 2:
                textfieldCell.textLabel.text = RichLocaleString(@"Account");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom] name];
                break;
            
            case 3:
                code = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom] currencyCode];
                textfieldCell.textLabel.text = RichLocaleString(@"Amount");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:code], transaction.amount];
                break;
            
            case 4:
                textfieldCell.textLabel.text = RichLocaleString(@"Property");
                textfieldCell.textfield.inputView = transPropertyPicker;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [[RichDelegate core] stringFromTransactionProperty:transaction.property];
                break;
            
            case 5:
                tableCellStyle = RichTableCellStyleDefault;
                cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
                
                cell.textLabel.text = RichLocaleString(@"Installment");
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                if (self.mode == RichTableModeUpdate) {
                    if (installmentEditor.isModified)
                        cell.detailTextLabel.text = (installmentEditor.times > 1) ? @"Yes" : @"No";
                    else
                        cell.detailTextLabel.text = (transaction.installmentPaymentTimes > 1) ? @"Yes" : @"No";
                }
                else
                    cell.detailTextLabel.text = (installmentEditor.checkCorrectness && installmentEditor.times > 1) ? @"Yes" : @"No";
                
                if (transaction.amount > 0) {
                    cell.userInteractionEnabled = YES;
                    cell.detailTextLabel.textColor = [UIColor blackColor];
                }
                else {
                    cell.userInteractionEnabled = NO;
                    cell.detailTextLabel.textColor = [UIColor grayColor];
                }
                break;
                
            case 6:
                textfieldCell.textLabel.text = RichLocaleString(@"Receipt No.");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeASCIICapable;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = nil;
                textfieldCell.textfield.text = transaction.receiptNo;
                break;
                
            case 7:
                textfieldCell.textLabel.text = RichLocaleString(@"No. of Receipts");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeNumberPad;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = nil;
                textfieldCell.textfield.text = [NSString stringWithFormat:@"%lu", transaction.numberOfReceipts];
                break;
                
            case 8:
                textfieldCell.textLabel.text = RichLocaleString(@"Comment");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDefault;
                textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                textfieldCell.textfield.inputView = nil;
                
                if (transaction.installmentPaymentTimes > 1 && self.mode == RichTableModeCreate)
                    textfieldCell.textfield.text = [NSString stringWithFormat:@"%@ (%lu/%lu)",
                                                    transaction.comment,
                                                    transaction.installmentMade,
                                                    transaction.installmentPaymentTimes];
                else
                    textfieldCell.textfield.text = transaction.comment;
                break;
        }
    }
    else if (self.mode == RichTableModeListEditable) {
        tableCellStyle = RichTableCellStyleValue;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        RichTransactionGeneral *trans = nil;
        
        if ([expendTransactions count] > 0)
            trans = [expendTransactions objectAtIndex:[indexPath row]];
        
        if (trans) {
            code = [[[RichDelegate core] accounts:accounts findAccountByID:trans.accountFrom] currencyCode];
            
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ %@",
                                   [[RichDelegate core] stringFromDate:trans.date format:@"MM/dd"],
                                   [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:trans.categoryCode]],
                                   trans.installmentPaymentTimes > 1 ?
                                        [NSString stringWithFormat:@"(%lu/%lu)", trans.installmentMade, trans.installmentPaymentTimes] : @""];
            
            if (trans.installmentMade == 1)
                cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:trans.installmentDownPayment code:code];
            else {
                cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:trans.amount + ((int)(((trans.amount * trans.installmentPaymentTimes) - trans.installmentDownPayment) * trans.installmentRate) / 100) code:code];
            }
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.userInteractionEnabled = YES;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        RichTransactionGeneral *trans = [expendTransactions objectAtIndex:[indexPath row]];
        uint64_t transId = trans.transId;
        uint64_t installmentTransId = trans.installmentTransId;
        
        if (installmentTransId == 0) {
            [[RichDelegate core] deleteTransactionWithCondition:[NSString stringWithFormat:@"installment_trans_id = %lld", transId]
                                                           type:kTransactionTypeGeneral];
            [[RichDelegate core] deleteTransaction:transId
                                              type:kTransactionTypeGeneral];
        }
        else {
            [[RichDelegate core] deleteTransactionWithCondition:[NSString stringWithFormat:@"installment_trans_id = %lld", installmentTransId]
                                                           type:kTransactionTypeGeneral];
            [[RichDelegate core] deleteTransaction:installmentTransId
                                              type:kTransactionTypeGeneral];
        }
        
        [expendTransactions removeObject:trans];
        
        if ([expendTransactions count] == 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else {
            self.navigationItem.rightBarButtonItem = nil;
            [self setEditing:NO];
        }
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    if (tableView.tag == RichTableViewTagCategory) {
        /* 
         * Called by CategoryViewController
         */
        
        currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
    }
    else if (tableView.tag == RichTableViewTagAccount) {
        /*
         * Called by AccountViewController
         */
        
        currentTextfield.text = accountPicker.account.name;
        
        if (installmentEditor) {
            RichAccount *transAccount = [[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom];
            if (transAccount)
                installmentEditor.currencyCode = transAccount.currencyCode;
        }
    }
    else {
        /*
         * Called by self
         */
        
        if (self.mode == RichTableModeListEditable) {
            ExpendViewController *evc = [[ExpendViewController alloc] initWithStyle:UITableViewStylePlain];
            evc.transaction = [expendTransactions objectAtIndex:[indexPath row]];
            evc.mode = RichTableModeUpdate;
            evc.navigator = self.navigator;
            [self.navigator pushViewController:evc animated:YES];
            [evc release];
        }
        else if (self.mode == RichTableModeListReadonly) {
            // TODO: passing something to caller?
            [self.callerDelegate tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath];
        }
        else if (self.mode == RichTableModeUpdate || self.mode == RichTableModeCreate) {
            if ([indexPath row] == 5) {
                /* Installment setting */
                
                [tableView deselectRowAtIndexPath:indexPath animated:YES];
                
                if (installmentEditor.date == nil)
                    installmentEditor.date = datePicker.date;
                installmentEditor.amount = transaction.amount;
                
                if (self.mode == RichTableModeUpdate && installmentEditor.isModified == NO) {
                    installmentEditor.times = transaction.installmentPaymentTimes;
                    installmentEditor.downPayment = transaction.installmentDownPayment;
                    installmentEditor.period = transaction.installmentPeriod;
                    installmentEditor.annualInterestRate = transaction.installmentRate;
                }
                
                [self.navigator pushViewController:installmentEditor animated:YES];
                //self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }
        }
    }
}

#pragma mark - Toolbar button actions

- (void)toolbarDidPressBackButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 1) {
        /* Category */
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CategoryNotificationBackToUpperLevel" object:nil];
    }
}

- (void)toolbarDidPressNextButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0) {
        /* Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    }
    else if (currentTextfield.tag == 1) {
        /* Category */
        if (categoryPicker.currentCode > 0) {
            currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
            categoryPicker.level = 1;
            categoryPicker.parentCode = RootCategoryExpend;
        }
    }
    else if (currentTextfield.tag == 2) {
        /* Account */
        if (accountPicker.account)
            currentTextfield.text = accountPicker.account.name;
    }
    
    [super toolbarDidPressNextButton:sender];
}

- (void)toolbarDidPressDoneButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0)
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    else if (currentTextfield.tag == 1) {
        if (categoryPicker.currentCode > 0) {
            currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
            categoryPicker.level = 1;
            categoryPicker.parentCode = RootCategoryExpend;
        }
    }
    else if (currentTextfield.tag == 2)
        if (accountPicker.account)
            currentTextfield.text = accountPicker.account.name;
    
    [super toolbarDidPressDoneButton:sender];
}

#pragma mark - Textfield delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    if (self.mode == RichTableModeUpdate)
        if (textField.tag == 0)
            datePicker.date = transaction.date;
    
    if (textField.tag == 3 || textField.tag == 7)
        if ([textField.text isEqualToString:@"0"])
            textField.text = @"";
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [super textFieldDidEndEditing:textField];
    
    if (transaction == nil) {
        transaction = [[RichTransactionGeneral alloc] init];
        transaction.date = datePicker.date;
        transaction.accountTo = 0;
    }
    
    switch (textField.tag) {
        case 0:
            transaction.date = datePicker.date;
            break;
        case 1:
            if (categoryPicker.currentCode)
                transaction.categoryCode = categoryPicker.currentCode;
            break;
        case 2:
            if (accountPicker.account.accountId)
                transaction.accountFrom = accountPicker.account.accountId;
            break;
        case 3:
            if ([textField.text isEqualToString:@""])
                textField.text = @"0";
            
            transaction.amount = [textField.text floatValue];
            installmentEditor.date = transaction.date;
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:0]]
                                  withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case 4:
        case 5:
            break;
        case 6:
            transaction.receiptNo = textField.text;
            
            if (![transaction.receiptNo isEqualToString:@""])
                if (transaction.numberOfReceipts == 0)
                    transaction.numberOfReceipts = 1;
            
            break;
        case 7:
            if ([textField.text isEqualToString:@""])
                textField.text = @"0";
            
            transaction.numberOfReceipts = [textField.text intValue];
            if (![transaction.receiptNo isEqualToString:@""])
                if (transaction.numberOfReceipts == 0)
                    transaction.numberOfReceipts = 1;
            
            break;
        case 8:
            transaction.comment = textField.text;
            break;
    }
}

#pragma mark - Picker view delegate and datasource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)tableComponents
{
    [super pickerView:pickerView didSelectRow:row inComponent:tableComponents];
    
    transaction.property = row;
}

#pragma mark - RichTableViewController Delegate

- (void)didPressCreate
{
    ExpendViewController *evc = [[ExpendViewController alloc] initWithStyle:UITableViewStylePlain];
    evc.mode = RichTableModeCreate;
    evc.navigator = self.navigator;
    [self.navigator pushViewController:evc animated:YES];
    [evc release];
}

- (void)didPressCreateDone
{
    if (installmentEditor.isModified && installmentEditor.checkCorrectness) {
        transaction.installmentPaymentTimes = installmentEditor.times;
        transaction.installmentDownPayment = installmentEditor.downPayment;
        transaction.installmentPeriod = installmentEditor.period;
        transaction.installmentRate = installmentEditor.annualInterestRate;
    }
    else {
        transaction.installmentPaymentTimes = 0;
        transaction.installmentDownPayment = 0.0f;
        transaction.installmentPeriod = 0;
        transaction.installmentRate = 0.0f;
    }
    
    if ([[RichDelegate core] createGeneralTransaction:transaction] <= 0) {
        NSLog(@"Create transaction failed");
        
        // TODO: [General Transaction] create transaction error handling
    }
    else {
        [expendTransactions addObject:transaction];
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    
    [transaction release];
    transaction = nil;
    
    [installmentEditor reset];
    
    [self.navigator popViewControllerAnimated:YES];
}

- (void)didPressUpdateDone
{
    if (installmentEditor.isModified && installmentEditor.checkCorrectness) {
        transaction.installmentPaymentTimes = installmentEditor.times;
        transaction.installmentDownPayment = installmentEditor.downPayment;
        transaction.installmentPeriod = installmentEditor.period;
        transaction.installmentRate = installmentEditor.annualInterestRate;
    }
    
    if ([[RichDelegate core] updateGeneralTransaction:transaction] < 0) {
        NSLog(@"Update transaction failed");
        // TODO: [General Transaction] update transaction error handling
    }
    
    [transaction release];
    transaction = nil;
    
    [installmentEditor reset];
    
    [self.navigator popViewControllerAnimated:YES];
}

@end
